<?php
namespace admin\action;

use herosphp\http\HttpRequest;
use api\utils\PayMpeApiClient;
use api\utils\MpeApiClient;

use herosphp\core\Loader;
use herosphp\utils\ArrayUtils;
/**
 * 销售 action
 * @package admin\action
 * @author yu
 */
class SaleAction extends CommonAction {


    //销售排行列表页面
    public function ranking( HttpRequest $request ) {

        $page = $request->getParameter('page');
        $pagesize = $request->getParameter('pagesize');

        if ($page <= 0) $page = 1;
        if ($pagesize <= 0) $pagesize = 15;
        $this->page=$page;
        $this->pagesize=$pagesize;

        $search_arr = array(
            "select_mix_option1" => $request->getParameter('select_mix_option1', 'trim'),
            "select_mix_option_value1" => $request->getParameter('select_mix_option_value1', 'trim'),
            "start_time" => $request->getParameter('start_time', 'trim'),
            "end_time" => $request->getParameter('end_time', 'trim'),
        );

        $this->assign('tableHeader', array('排行','货号','类型','品名','厂家','牌号','包装规格(KG/袋)','销售量(t)', '销售额(￥)', '利润(￥)'));
        if ( $request->getParameter('__export') == 1 ) {

            $this->setConditions($search_arr);
            $this->export($request); //导出数据

        } else { //加载视图显示数据

            $url = "api/sale/searchByRanking";
            $result = MpeApiClient::send($url, array('pagesize'=>$pagesize,'page'=>$page,'search_arr'=>$search_arr));
            if ( $result->isSucess() ) {
                $arr = $result->getData();
            } else {
                $arr = array();
                error_log($result->getMessage());
            }

            $items = $arr['items'];
            $itemsLen = count($items);
            for ($i = 0; $i < $itemsLen; $i++) {

                $items[$i]['total_sale_profit'] = $items[$i]['total_sale_amount']-$items[$i]['total_cost_price'];
            }

            $this->generatePageMenu($arr['total']);
            $this->assign('items', $items);
            $this->assign('search_arr', $search_arr);
            $this->setView('trading/sale_ranking_index');
            $this->assign('breadcrumb', array('报表管理', '销售排行'));
            $this->assign("title", "销售排行");
            $this->assign('breadcrumb', array('报表管理',$this->getTemplateVar('title')));
            $this->assign('breadUrl', array('javascript:;','javascript:;'));
        }

    }

    //销售明细列表页面
    public function details( HttpRequest $request ) {

        $page = $request->getParameter('page');
        $pagesize = $request->getParameter('pagesize');

        if ($page <= 0) $page = 1;
        if ($pagesize <= 0) $pagesize = 15;
        $this->page=$page;
        $this->pagesize=$pagesize;

        $search_arr = array(
            "select_mix_option1" => $request->getParameter('select_mix_option1'),
            "select_mix_option_value1" => urldecode($request->getParameter('select_mix_option_value1')),
            "start_time" => $request->getParameter('start_time'),
            "end_time" => $request->getParameter('end_time'),
            "appid"=>$request->getParameter('appid'),
        );

        $this->assign('tableHeader', array('订单号','租户标识','支付方式','货号','类型', '品名', '厂家','牌号','包装规格(KG/袋)','销售量(t)', '销售额(￥)', '利润(￥)', '销售时间'));
        if ( $request->getParameter('__export') == 1 ) { //导出数据

            $this->setConditions($search_arr);
            $this->export($request);

        } else { //加载视图显示数据

            $url = "api/sale/searchByDetails";
            $result = MpeApiClient::send($url, array('pagesize'=>$pagesize,'page'=>$page,'search_arr'=>$search_arr));

            if ( $result->isSucess() ) {
                $arr = $result->getData();
            } else {
                $arr = array();
                error_log($result->getMessage());
            }

            $items = $arr['items'];
            $this->fillInfo($items);
            $app_idoptions = Loader::model('AppInstallLog')->getItems('id,company_name');
            $this->assign('app_idoptions', $app_idoptions);
            $this->generatePageMenu($arr['total']);

            $this->assign('items', $items);
            $this->assign('search_arr', $search_arr);
            $this->setView('trading/sale_details_index');
            $this->assign('breadcrumb', array('报表管理', '销售明细'));
            $this->assign("title", "销售明细");
            $this->assign('breadcrumb', array('报表管理',$this->getTemplateVar('title')));
            $this->assign('breadUrl', array('javascript:;','javascript:;'));
        }

    }

    /**
     * 填充信息
     * @param $items
     */
    protected function fillInfo(&$items) {
        if (!empty($items)) {
            $ids = array();
            foreach ($items as $val) {
                $ids[] = $val['app_id'];
            }
            $model = Loader::model("AppInstallLog");
            $appInstallLogs = $model->getItems(array('id' => array('$in' => $ids)));
            $appInstallLogs = ArrayUtils::changeArrayKey($appInstallLogs, 'id');
            foreach ($items as $key => $value) {
                $items[$key]['company_name'] = $appInstallLogs[$value['app_id']]['company'];

            }
        }
    }

    //财务统计页面
    public function finance( HttpRequest $request ) {

        $page = $request->getParameter('page');
        $pagesize = $request->getParameter('pagesize');

        if ($page <= 0) $page = 1;
        if ($pagesize <= 0) $pagesize = 15;
        $this->page=$page;
        $this->pagesize=$pagesize;

        $search_arr = array(
            "select_mix_option1" => $request->getParameter('select_mix_option1'),
            "select_mix_option_value1" => urldecode($request->getParameter('select_mix_option_value1')),
            "start_time" => $request->getParameter('start_time'),
            "end_time" => $request->getParameter('end_time'),
            "appid"=>$request->getParameter('appid'),

        );

        $this->assign('tableHeader', array('日期','租户标识','销售总额(￥)','成本总额(￥)','利润(￥)', '查看'));
        if ( $request->getParameter('__export') == 1 ) { //导出数据

            $this->setConditions($search_arr);
            $this->export($request);

        } else { //加载视图

            $url = "api/sale/searchByFinance";
            $result = MpeApiClient::send($url, array('pagesize'=>$pagesize,'page'=>$page,'search_arr'=>$search_arr));

            if ( $result->isSucess() ) {
                $arr = $result->getData();
            } else {
                $arr = array();
                error_log($result->getMessage());
            }

            $items = $arr['items'];
            $this->fillInfo($items);

            $app_idoptions = Loader::model('AppInstallLog')->getItems('id,company_name');
            $this->assign('app_idoptions', $app_idoptions);

            $this->generatePageMenu($arr['total']);
            $this->assign('items', $items);
            $this->assign('search_arr', $search_arr);

            $this->setView('trading/sale_finance_index');
            $this->assign("title", "财务统计");
            $this->assign('breadcrumb', array('报表管理',$this->getTemplateVar('title')));
            $this->assign('breadUrl', array('javascript:;','javascript:;'));
        }

    }

    //导出数据
    protected function export(HttpRequest $request) {
        if( $request->getParameter('__export') == 1 ){
            $ids = $request->getParameter('ids');
            if( $ids ){
                $conditions['id']['$in']=$ids;
                $this->setConditions($conditions);
            }
            $excel = array();
            if ( $request->getMethod() == 'ranking' ) {
                $url = "api/sale/searchByRanking";
                $result = MpeApiClient::send($url, array('pagesize'=>getConfig('export_max_count'),'page'=>1,'search_arr'=>$this->getConditions()));
                foreach($result->getItems() as $k => $v)
                {
                    $tmp = array();
                    $tmp[] = $k+1;
                    $tmp[] = $v["product_no"];
                    $tmp[] = $v["type_name"];
                    $tmp[] = $v["product_name"];
                    $tmp[] = $v["factory_name"];
                    $tmp[] = $v["brand_name"];
                    $tmp[] = $v["pkg_size"];
                    $tmp[] = $v["total_sale_quantity"];
                    $tmp[] = $v["total_sale_amount"];
                    $tmp[] = number_format($v['total_sale_amount'] - $v["total_cost_price"], 2, '.', '');
                    $excel[] = $tmp;
                }
                $title = '销售排行';

            } elseif ($request->getMethod() == 'details') {

                $url = "api/sale/searchByDetails";
                $result = MpeApiClient::send($url, array('pagesize'=>getConfig('export_max_count'),'page'=>1,'search_arr'=>$this->getConditions()));
                $items = $result->getItems();
                $this->fillInfo($items);
                foreach($items as $k => $v)
                {
                    $tmp = array();
                    $tmp[] = $v["order_no"];
                    $tmp[] = $v["company_name"];
                    $tmp[] = $v["pay_way"];
                    $tmp[] = $v["product_no"];
                    $tmp[] = $v["type_name"];
                    $tmp[] = $v["product_name"];
                    $tmp[] = $v["factory_name"];
                    $tmp[] = $v["brand_name"];
                    $tmp[] = $v["pkg_size"];
                    $tmp[] = $v["sale_quantity"];
                    $tmp[] = $v["sale_amount"];
                    $tmp[] = $v["sale_profit"];
                    $tmp[] = $v["order_time"];
                    $excel[] = $tmp;
                }
                $title = '销售明细';

            } elseif ( $request->getMethod() == 'finance' ) {

                $url = "api/sale/searchByFinance";
                $result = MpeApiClient::send($url, array('pagesize'=>getConfig('export_max_count'),'page'=>1,'search_arr'=>$this->getConditions()));
                $items = $result->getItems();
                $this->fillInfo($items);
                foreach($items as $k => $v)
                {
                    $tmp = array();
                    $tmp[] = $v["that_day"];
                    $tmp[] = $v["company_name"];
                    $tmp[] = $v["sales_price"];
                    $tmp[] = $v["cost_price"];
                    $tmp[] = $v["profit"];
                    $excel[] = $tmp;
                }
                $title = '财务统计';

            }
            $header = $this->getTemplateVar('tableHeader');
            phpexcel($title,$header,$excel);
            exit();
        }
    }
}
